﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;

namespace Silverchunks
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            WebRequest.RegisterPrefix("http:", System.Net.Browser.WebRequestCreator.ClientHttp);
        }

        private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            int maxSeq = 0;
            Guid fileUploadKey = Guid.Empty;
            UploadService.UploadServiceClient client = new UploadService.UploadServiceClient();
            client.BeginUploadCompleted += new EventHandler<UploadService.BeginUploadCompletedEventArgs>((s, e1) =>
            {
                fileUploadKey = e1.Result;
                FileInfo fileInfo = e1.UserState as FileInfo;
                using (var fs = fileInfo.OpenRead())
                {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    int seq = 0;
                    while ((bytesRead = fs.Read(buffer, 0, 4096)) > 0)
                    {
                        UploadService.Chunk chunk = new UploadService.Chunk();
                        chunk.Data = buffer;
                        chunk.Sequence = seq;
                        chunk.UploadKey = fileUploadKey;
                        maxSeq = seq;
                        client.UploadChunksAsync(chunk, seq);
                        seq++;
                    }
                }
            });
            int chunksCompleted = 0;
            client.UploadChunksCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>((s, e2) =>
            {
                chunksCompleted++;
                if (chunksCompleted == maxSeq)
                {
                    client.EndUploadAsync(fileUploadKey);
                }
            });
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() ?? true)
            {
                client.BeginUploadAsync(ofd.File.Name, ofd.File);
            }
        }
    }
}
